﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Kiiro.Common.Entities;
using Kiiro.Common.Utility;
using Kiiro.Model;
using Kiiro.SiteDefinition.ControlTemplates;
using Kiiro.SiteDefinition.Core;
using System.Web.UI;
using Microsoft.SharePoint.Utilities;
using System.Web.UI.HtmlControls;

namespace Kiiro.SiteDefinition.ProjectPages
{
    public partial class Team : BasePage
    {
        private List<TeamMember> teamMembers = new List<TeamMember> ( );
        public List<TeamMember> TeamMembers
        {
            get { return teamMembers; }
            set { teamMembers = value; }
        }

        public NavigationSub NavigationSub
        {
            get { return KiiroMaster.NavigationSub; }
        }

        public Pager V2Pager
        {
            get { return ( Pager ) v2Pager; }
        }

        protected void Page_Load ( object sender, EventArgs e )
        {
            AddCommandButtons ( );

            litTitle.Text = "Team";
            if ( KiiroMaster.V2Header.Project != null && !string.IsNullOrEmpty ( KiiroMaster.V2Header.Project.Title ) )
            {
                litTitle.Text = KiiroMaster.V2Header.Project.Title + " - Team";
            }

            V2Pager.NextClick += new EventHandler ( RePopulatePage );
            V2Pager.PrevClick += new EventHandler ( RePopulatePage );
            V2Pager.EntitiesPerPageChange += new EventHandler ( RePopulatePage );

            teamMembers = TeamModel.GetTeamMembers ( SiteCollectionId, ServerRelativeUrl );

            if ( !IsPostBack )
            {
                V2Pager.SortExpression = "Name";
                PopulatePage ( );
            }
        }

        #region Page Related Methods

        private void PopulatePage ( )
        {
            if ( TeamMembers.Count > 0 )
            {
                SortList ( );

                V2Pager.PopulatePager ( TeamMembers.Count, Constants.PagerEntity.TeamMembers );

                rptTeam.DataSource = TeamMembers.GetRange ( V2Pager.PagingIndex, V2Pager.DisplayedCount );
                rptTeam.DataBind ( );

                if ( rptTeam.Items.Count > 0 )
                {
                    HtmlTableRow trTeam = ( HtmlTableRow ) rptTeam.Items [ rptTeam.Items.Count - 1 ].FindControl ( "trTeam" );
                    trTeam.Attributes.Add ( "class", "borderless" );
                }
                else
                {
                    v2Pager.Visible = false;
                    columnHeaders.Visible = false;
                }
            }
        }

        private void AddCommandButtons ( )
        {
            if ( PermissionBitsTeams [ 0 ] )
            {
                List<LinkButton> buttons = new List<LinkButton> ( );

                LinkButton btnCreate = new LinkButton ( );
                btnCreate.Text = "Add A Team Member";
                btnCreate.Attributes.Add ( "class", "icon-add" );
                btnCreate.Click += new EventHandler ( btnCreate_Click );
                NavigationSub.Commands.Add ( btnCreate );
            }
        }

        protected void btnCreate_Click ( object sender, EventArgs e )
        {
            Response.Redirect ( ServerRelativeUrl + Constants.ProjectFileUrls.TeamMemberNew );
        }

        protected void btnDelete_Click ( object sender, EventArgs e )
        {
            LinkButton btnDelete = ( LinkButton ) sender;
            int id = int.Parse ( btnDelete.CommandArgument );

            TeamMember member = TeamMembers.Find ( x => x.Id == id );

            if ( member != null )
            {
                member.EditType = EditType.Deleted;
                member.ServerRelativeUrl = ServerRelativeUrl;
                member.ModifiedBy = CurrentUser;
                member = TeamModel.Save ( member, SiteCollectionId, ServerRelativeUrl );
            }

            if ( member.IsValid ( ) )
                Response.Redirect ( String.Format ( "{0}/Team.aspx", ServerRelativeUrl ) );
            else
            {
                KiiroMaster.V2ErrorsList.ErrorMessages.Add ( FormattingHelpers.GetErrorMessageText ( member.IsProjectManagerMessage ) );
                KiiroMaster.V2ErrorsList.ErrorMessages.Add ( FormattingHelpers.GetErrorMessageText ( member.EditTypeMessage ) );
            }
        }

        protected void rptTeam_ItemDataBound ( object source, RepeaterItemEventArgs e )
        {
            TeamMember teamMember = ( TeamMember ) e.Item.DataItem;

            Label txtProjectRole = ( Label ) e.Item.FindControl ( "txtProjectRole" );
            if ( txtProjectRole != null )
            {
                txtProjectRole.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( teamMember.RoleOnProject );
                if (txtProjectRole.Text.Length > 72)
                {
                    txtProjectRole.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( txtProjectRole.Text.Substring ( 0, 70 ) ) + "...";
                }
            }

            Label txtProjectManager = ( Label ) e.Item.FindControl ( "txtProjectManager" );
            if ( txtProjectManager != null )
            {
                txtProjectManager.Text = FormattingHelpers.BooleanToDisplayString ( teamMember.IsProjectManager );
            }

            HyperLink lnkDisplayUserName = ( HyperLink ) e.Item.FindControl ( "lnkDisplayUserName" );
            if ( lnkDisplayUserName != null )
            {
                lnkDisplayUserName.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( teamMember.User.FullName );
                lnkDisplayUserName.NavigateUrl = String.Format ( "{0}{1}?id={2}",
                    ServerRelativeUrl, Constants.PortalFileUrls.UserDisplay, teamMember.User.SPUserId );
            }

            Label txtPhone = ( Label ) e.Item.FindControl ( "txtPhone" );
            if ( txtPhone != null )
            {
                txtPhone.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( teamMember.User.PhoneNumber );
            }

            HyperLink lnkEmail = ( HyperLink ) e.Item.FindControl ( "lnkEmail" );
            if ( lnkEmail != null )
            {
                string safeEmail = SPHelpers.ConvertHtmlToKiiroSafeText ( teamMember.User.Email );
                lnkEmail.Text = safeEmail;
                lnkEmail.NavigateUrl = string.Format ( "mailto:{0}", safeEmail );
            }

            Label txtIM = ( Label ) e.Item.FindControl ( "txtIM" );
            if ( txtIM != null )
            {
                txtIM.Text = SPHelpers.ConvertHtmlToKiiroSafeText ( teamMember.User.IM );
            }

            Image imgPerson = ( Image ) e.Item.FindControl ( "imgPerson" );
            if ( imgPerson != null )
            {
                imgPerson.ImageUrl = teamMember.User.PictureUrl ?? "/_layouts/images/Kiiro/person-thumb.gif";
            }
            HyperLink lnkImageDisplayUser = ( HyperLink ) e.Item.FindControl ( "lnkImageDisplayUser" );
            if ( lnkImageDisplayUser != null )
            {
                lnkImageDisplayUser.NavigateUrl = String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.ProjectFileUrls.UserDisplay, teamMember.User.SPUserId );
            }

            HyperLink lnkEdit = ( HyperLink ) e.Item.FindControl ( "lnkEdit" );
            if ( lnkEdit != null )
            {
                bool editSelf = PermissionsModel.CanTeamMemberUpdateThemselves ( CurrentUser, teamMember, SiteCollectionId, ServerRelativeUrl );

                if ( ( PermissionBitsTeams [ 2 ] ) || ( editSelf && teamMember.User.Id == CurrentUser.Id ) )
                {
                    lnkEdit.Visible = true;
                    lnkEdit.NavigateUrl = String.Format ( "{0}{1}?id={2}", ServerRelativeUrl, Constants.ProjectFileUrls.TeamMemberEdit, teamMember.Id );
                }
                else
                    lnkEdit.Visible = false;
            }

            LinkButton btnDelete = ( LinkButton ) e.Item.FindControl ( "btnDelete" );
            if ( btnDelete != null )
            {
                btnDelete.Visible = ( PermissionBitsTeams [ 3 ] && teamMember.User.Login != CurrentUser.Login );
                if ( PermissionBitsTeams [ 3 ] )
                {
                    btnDelete.CommandArgument = teamMember.Id.ToString ( );
                }
            }

        }

        #endregion

        #region Pager Related Methods

        private void SortList ( )
        {
            pmSort.Visible = false;
            roleSort.Visible = false;
            nameSort.Visible = false;

            Literal sortText = nameSort;
            string sortTextTemplate = "<img src='/_layouts/images/Kiiro/icon-sort-{0}.gif' />";

            switch ( V2Pager.SortExpression )
            {
                case "PM":
                    sortText = pmSort;
                    teamMembers.Sort ( delegate ( TeamMember tm1, TeamMember tm2 ) { return tm1.IsProjectManager.CompareTo ( tm2.IsProjectManager ); } );
                    break;
                case "ProjectRole":
                    sortText = roleSort;
                    teamMembers.Sort ( delegate ( TeamMember tm1, TeamMember tm2 ) { return !string.IsNullOrEmpty ( tm1.RoleOnProject ) ? tm1.RoleOnProject.CompareTo ( tm2.RoleOnProject ) : string.Empty.CompareTo ( tm2.RoleOnProject ); } );
                    break;
                case "Name":
                default:
                    sortText = nameSort;
                    teamMembers.Sort ( delegate ( TeamMember tm1, TeamMember tm2 ) { return tm1.User.FullName.Trim ( ).CompareTo ( tm2.User.FullName.Trim ( ) ); } );
                    break;
            }

            sortText.Visible = true;

            if ( V2Pager.SortDirection == SortDirection.Ascending )
            {
                sortText.Text = string.Format ( sortTextTemplate, "asc" );
            }
            else
            {
                sortText.Text = string.Format ( sortTextTemplate, "desc" );
                teamMembers.Reverse ( );
            }
        }

        private void RePopulatePage ( object sender, EventArgs e )
        {
            PopulatePage ( );
        }

        protected void SortBy_Click ( object sender, EventArgs e )
        {
            LinkButton link = ( LinkButton ) sender;
            if ( V2Pager.SortDirection == SortDirection.Ascending && V2Pager.SortExpression == link.CommandArgument )
                V2Pager.SortDirection = SortDirection.Descending;
            else
                V2Pager.SortDirection = SortDirection.Ascending;
            V2Pager.SortExpression = link.CommandArgument;

            V2Pager.IsSortClick = true;
            V2Pager.DisplayedCount = rptTeam.Items.Count;
            PopulatePage ( );
        }

        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.SiteDefinition/12/TEMPLATE/FEATURES/Kiiro.ProjectPages/Team/Team.aspx.cs $
 * 
 * 28    2/08/10 2:28p Camerons
 * 
 * 27    1/12/10 2:33p Camerons
 * 
 * 26    1/06/10 12:39p Camerons
 * 
 * 25    29/10/09 3:04p Camerons
 * 
 * 24    29/10/09 2:55p Camerons
 * 
 * 23    10/26/09 9:40a Adamw
 * 
 * 22    10/23/09 5:53p Adamw
 * Case 348
 * 
 * 21    15/10/09 1:11p Shafia
 * 
 * 20    30/09/09 4:08p Camerons
 * Update all links that point to UserPages, pass User.SPUserId as the
 * ItemId so that we can safely run GetOrCreateUser
 * 
 * 19    25/09/09 10:44a Shafia
 * fixed sort method to retain page index and display correct number of
 * rows when sort is clicked.
 * 
 * 18    22/09/09 10:21a Shafia
 * member image now is a link to member page
 * 
 * 17    21/09/09 12:42p Shafia
 * 
 * 16    18/09/09 2:33p Shafia
 * New Pager Implemented. All data binding is done on the page itself not
 * on the Pager control
 * 
 * 15    31/08/09 12:20p Shafia
 * 
 * 14    17/08/09 11:07a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/